<?php
declare (strict_types = 1);

namespace app\im\controller;

use Swoole\WebSocket\Frame;
use think\Request;
use think\swoole\Websocket;

class Notice
{
    public function index()
    {
        return \think\swoole\helper\websocket()
            ->onOpen(function ($request) {
                // 连接建立
                var_dump('建立通知连接');
            })
            ->onMessage(function (Websocket $websocket, Frame $frame) {
                $data = json_decode($frame->data, true);
                // 聊天逻辑处理
                $websocket->emit('chat', ['msg' => $data['msg'] ?? '']);
            })
            ->onClose(function ($server, $fd) {
                // 连接关闭
                var_dump('关闭连接');
            });
    }
}
